trigger SyncJointCallToCalendar on JointCall__c ( after insert, after update ,before delete ) {
   
    if(system.trigger.isinsert){
        recordtype CallPlanRecordType=[select id,sobjecttype,developername from recordtype where sobjecttype=:'event' and developername=:'CallPlan' limit 1];
        list<event> insertEvent=new list<event>();
        set<Date> SortDate=new set<date>();
        set<id> ownerId=new set<id>();
        for(JointCall__c t:trigger.new){
            Event e = new Event(Subject='协同拜访', 
                                        WhatId=t.id,
                                        recordtypeid=CallPlanRecordType.id,
                                        ownerid=t.Owner__c,
                                        StartDateTime=datetime.newInstancegmt(t.CallDate__c.year(),t.CallDate__c.month(),t.CallDate__c.day(), 0, 0, 0),
                                        EndDateTime=datetime.newInstancegmt(t.CallDate__c.year(),t.CallDate__c.month(),t.CallDate__c.day(), 0, 30, 0),
                                        IsReminderSet = false,
                                        eventDate__c=t.CallDate__c,
                                        hospitalname__c=t.HospitalID__c
                                         );
             insertEvent.add(e);
             sortDate.add(t.CallDate__c);
             ownerId.add(t.owner__c);
        }
        //system.assert(false,insertevent);
        insert insertEvent;
        CalendarSorter.sort(sortDate,Ownerid);
        
    }
    
    
    
    if(system.trigger.isdelete){
        list<id> JointCallId=new list<id>();
        set<Date> SortDate=new set<date>();
        set<id> ownerId=new set<id>();
        for(Jointcall__c t:trigger.old){
            JointCallId.add(t.id);
            sortdate.add(t.CallDate__c);
            ownerid.add(t.owner__c);
        }
        list<event> EventList=[select id from event where WhatId in: JointCallId];
        if(eventlist.size()>0){
            delete eventlist;
        }
        CalendarSorter.sort(sortDate,Ownerid);
    }
  
}